package com.lidx.back.statistics.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.lidx.back.statistics.commons.Constants;
import com.lidx.back.statistics.commons.MaterialUpdateConfig;
import com.lidx.back.statistics.commons.SpringContextHolder;
import com.lidx.back.statistics.commons.config.Global;
import com.lidx.back.statistics.controller.MaterialUpdateRequestBean;
import com.lidx.back.statistics.controller.admin.MaterialIconJson;
import com.lidx.back.statistics.dao.ILatestMaterialDao;
import com.lidx.back.statistics.dao.IMaterialDao;
import com.lidx.back.statistics.entity.MaterialLatest;
import com.lidx.back.statistics.entity.MaterialPO;
import com.lidx.back.statistics.entity.MaterialUpdateRequestInfo;
import com.lidx.back.statistics.service.IMaterialService;
import com.lidx.back.statistics.utils.FileUtils;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class MaterialServiceImpl implements IMaterialService {

	private static final Logger logger = LoggerFactory.getLogger(MaterialServiceImpl.class);
	
	@Autowired
	private IMaterialDao materialDao;
	@Autowired
	private ILatestMaterialDao latestMaterialDao;

	@Autowired
	private MaterialUpdateConfig materialUpdateConfig;
	@Transactional(readOnly=true)
	public List<MaterialPO> findAllMaterialList(String versionType, String versionNumber) {
		/*JSONObject jsonObject = new JSONObject();
		String materialJsonString = JedisUtils.get(Constants.REDIS_MATERIAL_LIST_KEY+versionType+versionNumber);
		if(!StringUtils.isEmpty(materialJsonString)){
			Object list = jsonObject.parseArray(materialJsonString, MaterialPO.class);
			if(list instanceof List){
				List<MaterialPO> redisMaterialList = (List)list;
				return redisMaterialList;
			}
		}*/
		List<MaterialPO> redisMaterials = materialDao.getAllMaterialPOs(versionType, versionNumber);
		/*materialJsonString = jsonObject.toJSONString(redisMaterials);
		JedisUtils.set(Constants.REDIS_MATERIAL_LIST_KEY+versionType+versionNumber, materialJsonString, 60*60);*/
		return redisMaterials;
	}

	public List<MaterialPO> findAllMaterialListByCategoryId(String versionType, String versionNumber, int categoryId) {
		MaterialPO mp = new MaterialPO();
		mp.setCategoryId(categoryId);
		mp.setVersionType(versionType);
		return materialDao.getMaterials(mp);
	}
	/*public List<MaterialPO> findAllMaterialListBySex(String versionType,
			String versionNumber, String sex) {
		MaterialPO mp = new MaterialPO();
		mp.setVersionType(versionType);
		mp.setVersionNumber(versionNumber);
		mp.setGender(sex);
		//List<MaterialPO> materials = materialDao.getMaterialPOsBySex(versionType, versionNumber,sex);
		List<MaterialPO> materials = materialDao.getMaterials(mp);
		*//*materialJsonString = jsonObject.toJSONString(redisMaterials);
		JedisUtils.set(Constants.REDIS_MATERIAL_LIST_KEY+versionType+versionNumber, materialJsonString, 60*60);*//*
		return materials;
	}*/

	/*public List<MaterialPO> findRecommendMaterials(String versionType,
			String versionNumber, String deviceId) {
		ClientInfo clientInfo = appInitDao.getClientInfo(deviceId);
		String sex = clientInfo.getSex();
		List<MaterialPO> materialPOs = materialDao.getRecommendMaterialPOs(versionType, versionNumber, sex);
		if(materialPOs != null)
			return materialPOs;
		return new ArrayList<MaterialPO>();
	}*/

	public void updateMaterialUpdateRequest(MaterialUpdateRequestInfo info) {
		info.setId(1);
		materialDao.updateRequest(info);
	}

	public MaterialUpdateRequestInfo getRequestInfo() {
		return materialDao.getRequestInfo();
	}

	@Transactional(readOnly=false,rollbackFor=Exception.class)
	public synchronized void updateMaterial(String versionType, String versionNumber) throws Exception {
		// 准备相关目录
		/*String workspaceRoot = materialUpdateConfig.getLocalWorkspace();
		if (!new File(workspaceRoot).exists()) {
			new File(workspaceRoot).mkdirs();
			if (!new File(workspaceRoot).exists()) {
				throw new Exception("workspaceRoot not exist: " + workspaceRoot);
			}
		}*/
		
		/*FTPClient ftpClient = new FTPClient();
		ftpClient.connect(materialUpdateConfig.getIisFtpHost());

		ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftpClient.setControlEncoding("utf-8");
		ftpClient.setControlKeepAliveReplyTimeout(300000);
		ftpClient.setConnectTimeout(300000);
		ftpClient.setControlKeepAliveTimeout(300000);
		ftpClient.enterLocalPassiveMode();
		
		ftpClient.configure(new FTPClientConfig("com.zznode.tnms.ra.c11n.nj.resource.ftp.UnixFTPEntryParser"));
		boolean loginResult = ftpClient.login(materialUpdateConfig.getFtpUserName(), materialUpdateConfig.getFtpPassword());
		if (!loginResult) {
			throw new Exception("ftp login failed. " + materialUpdateConfig.getIisFtpHost());
		}*/
		
		//String destFolderPath = workspaceRoot + DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMddHHmmss");
		/*String destFolderPath = workspaceRoot+"\\local";
		File destFolder = new File(destFolderPath);
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		} else{
			FileUtils.deleteQuietly(destFolder);
		}*/
		
		//boolean ftpChangeResult = ftpClient.changeWorkingDirectory(materialUpdateConfig.getIisFtpRoot()+versionType+"/"+versionNumber);
		
		String ftpMaterialPath = materialUpdateConfig.getFtpLocalRoot()+versionType+"\\"+versionNumber+"\\";
		String nginxRoot = Global.getConfig("nginx.root");
		String nginxLocalMaterialPath = nginxRoot + Constants.MATERIALS_DIRECTORY+"\\"+ versionType+"\\"+versionNumber+"\\";
		File nginxFileDir = new File(nginxLocalMaterialPath);
		if(!nginxFileDir.exists()){
			nginxFileDir.mkdirs();
			FileUtils.copyDirectory(new File(ftpMaterialPath), nginxFileDir,true);
		}else {
			FileUtils.copyDirectory(new File(ftpMaterialPath), nginxFileDir,true);
		}
		//FileUtils.copyDirectory(new File(ftpMaterialPath), destFolder,true);
		//.copyDirectoryToDirectory(new File(ftpMaterialPath), destFolder);
		
		/*FTPFile[] fs = ftpClient.listFiles(); 
        for(FTPFile ff:fs){ 
        	String ftpFileName = ff.getName();
        	long ftpFileSize = ff.getSize();
        	
            File localFile = new File(destFolderPath+"/"+ftpFileName); 
            
            if(localFile.exists()){
            	//String localFileMd5 = (String) materialFileMD5Cache.get(ftpFileName).getObjectValue();
            	if(localFile.length() == ftpFileSize){
            		continue;
            	}
            }
            OutputStream is = new FileOutputStream(localFile);  
            ftpClient.retrieveFile(ff.getName(), is); 
            is.close(); 
        } */
        List<MaterialUpdateRequestBean> materialRequests = parseMateralsInFolder(nginxFileDir,versionType,versionNumber);
        
        StringBuffer sb = new StringBuffer();
        List<MaterialIconJson> jsons = Lists.newArrayList();
        
        for (MaterialUpdateRequestBean request : materialRequests) {
        	boolean iconExist = false;
        	// icon
			File iconFile = request.getIconFile();
			String iconName = iconFile.getName();
			
			byte[] iconBytes = FileCopyUtils.copyToByteArray(iconFile);
			String iconMD5 = DigestUtils.md5DigestAsHex(iconBytes);
			
			String iconDownloadUrl = materialUpdateConfig.getIisURLRoot() + versionType + "/" + versionNumber + "/" + iconName;

			request.getMaterialPo().setIconName(iconName);
			request.getMaterialPo().setIconMD5(iconMD5);
			request.getMaterialPo().setIconDownloadUrl(iconDownloadUrl);
			
			// material
			File materialFile = request.getMaterialFile();
			String materialName = materialFile.getName();
			
			byte[] materialBytes = FileCopyUtils.copyToByteArray(materialFile);
			String materialMD5 = DigestUtils.md5DigestAsHex(materialBytes);
			
			String materialDownloadUrl = materialUpdateConfig.getIisURLRoot() + versionType + "/" + versionNumber + "/" + materialName;

			request.getMaterialPo().setMaterialName(materialName);
			request.getMaterialPo().setMaterialMD5(materialMD5);
			request.getMaterialPo().setMaterialDownloadUrl(materialDownloadUrl);
			
			for(MaterialIconJson json : jsons){
				if(json.getIconName().equalsIgnoreCase(iconName)){
					iconExist = true;
					break;
				}
			}
			if(iconExist){
				continue;//因为男性与女性会生成两份同样的iconjson文件，所以在此进行筛选，只留一份
			}
			/*MaterialIconJson iconJson = new MaterialIconJson();
			iconJson.setIconMD5(iconMD5);
			iconJson.setIconName(iconName);
			iconJson.setCategory(request.getMaterialPo().getCategory());
			iconJson.setIsRecommend(request.getMaterialPo().getIsRecommend());
			iconJson.setRecommendOrder(request.getMaterialPo().getRecommendOrder());
			iconJson.setCategoryOrder(request.getMaterialPo().getCategoryOrder());
			jsons.add(iconJson);*/
		} 
        Gson gson = new Gson();
        String outJson = gson.toJson(jsons);
        FileUtils.writeToFile("d:\\jsonfile\\jsonFile.txt", outJson, false);
        
		// 更新数据库：删除原版本相关素材积累，全部插入新纪录
		materialDao.deleteMaterials(versionType, versionNumber);
		List<MaterialPO> ms = Lists.newArrayList();
		for (MaterialUpdateRequestBean request : materialRequests) {
			MaterialPO materialPo = request.getMaterialPo();
			ms.add(materialPo);
			//materialService.updateMaterialById(materialPo, materialPo.getId());
		}
		materialDao.saveMaterials(ms);
		//materialDao.clearMaterialCacheRegion();
		//materialDao.saveMaterial(materialPo);
		materialDao.clearMaterialCacheRegion();
		/*CacheManager cacheManager = EhCacheUtils.getCacheManager();
		Cache materialCache= cacheManager.getCache("materialPO");
		Object o = materialCache.get("materials"+versionType+versionNumber);
		materialCache.remove("materials"+versionType+versionNumber);
		EhCacheUtils.put("materialPO", "materials"+versionType+versionNumber, materialDao.getAllMaterialPOs(versionType, versionNumber));*/
		
		logger.debug("database update finished",materialRequests);

		//FileSystemUtils.deleteRecursively(destFolder);
		//ftpClient.disconnect();
	}
	
	private List<MaterialUpdateRequestBean> parseMateralsInFolder(File folder, String versionType, String versionNumber) throws Exception {

		if (folder == null || !folder.exists() || !folder.canRead()) {
			throw new Exception("目录读取异常！" + folder);
		}

		File configFile = new File(folder.getAbsolutePath() + "\\" + materialUpdateConfig.getConfigFileName());

		if (!configFile.exists() || !configFile.canRead()) {
			throw new Exception("配置文件读取异常！" + configFile);
		}

		// 读文件
		Charset charset = Charset.forName("utf-8");
		List<String> lines = new ArrayList<String>();
		try {
			lines = Files.readLines(configFile, charset);
		} catch (Exception e) {
			throw new Exception("素材配置文件读取异常！");
		}

		// 版本类型
		/*String versionType = "";
		{
			try {
				String versionTypeStr = lines.get(1);
				if ("ios".equalsIgnoreCase(versionTypeStr)) {
					versionType = "ios";
				} else if ("android".equalsIgnoreCase(versionTypeStr)) {
					versionType = "android";
				} else {
					throw new Exception();
				}
			} catch (Exception e) {
				throw new Exception("素材配置文件中版本类型错误！" + versionType);
			}
		}*/

		// 版本号
		/*String versionNumber = "";
		{
			String versionNumStr = lines.get(3);
			if (versionNumStr != null && !StringUtils.isEmpty(versionNumStr.trim())) {
				versionNumber = versionNumStr.trim();
			} else {
				throw new Exception("素材配置文件中版本号错误！");
			}
		}*/

		// 素材文件
		List<MaterialUpdateRequestBean> materialRequests = new ArrayList<MaterialUpdateRequestBean>();
		{
			try {
				for (int i = 1; i < lines.size(); i++) {
					MaterialUpdateRequestBean materialRequest = new MaterialUpdateRequestBean();
					String lineStr = lines.get(i);
					if (lineStr != null && !StringUtils.isEmpty(lineStr.trim())) {
						String[] parts = lineStr.split(";");
						if (parts.length != 8) {
							throw new Exception("素材列表数据格式错误  == " + lineStr);
						}

						String uuid = parts[0].trim();
						if (!StringUtils.isEmpty(uuid)) {
							materialRequest.getMaterialPo().setUuid(uuid);
						} else {
							throw new Exception("UUID的参数值为空！  ==" + lineStr);
						}

						String iconName = parts[1].trim();
						File iconFile = new File(folder.getAbsolutePath() + "\\" + iconName);
						if (iconFile.exists()) {
							materialRequest.setIconFile(iconFile);
						} else {
							throw new Exception(iconName + "不存在！  ==" + lineStr);
						}

						String materialName = parts[2].trim();
						File materialFile = new File(folder.getAbsolutePath() + "\\" + materialName);
						if (materialFile.exists()) {
							materialRequest.setMaterialFile(materialFile);
						} else {
							throw new Exception(materialName + "不存在！  ==" + lineStr);
						}

						/*String isRecommend = parts[3].trim();
						String recommendOrder = parts[4].trim();
						if ("y".equalsIgnoreCase(isRecommend) && !StringUtils.isEmpty(recommendOrder)) {
							materialRequest.getMaterialPo().setIsRecommend("1");
							materialRequest.getMaterialPo().setRecommendOrder(recommendOrder);
						} else if ("n".equalsIgnoreCase(isRecommend)) {
							materialRequest.getMaterialPo().setIsRecommend("-1");
							materialRequest.getMaterialPo().setRecommendOrder("0");
						} else {
							throw new Exception("推荐字段标记错误  ==" + lineStr);
						}*/

						String categoryOrder = parts[5].trim();
						if (!StringUtils.isEmpty(categoryOrder)) {
							materialRequest.getMaterialPo().setCategoryOrder(Integer.valueOf(categoryOrder));
						} else {
							throw new Exception(" 类别顺序出错 ==" + categoryOrder);
						}
						
						/*String category = parts[6].trim();
						if (!StringUtils.isEmpty(category)) {
							materialRequest.getMaterialPo().setCategory(category);
						} else {
							throw new Exception(" 类别出错 ==" + category);
						}
						
						String gender = parts[7].trim();
						if (!StringUtils.isEmpty(gender)) {
							materialRequest.getMaterialPo().setGender(gender);
						} else {
							throw new Exception(" 性别出错 ==" + category);
						}*/

						materialRequest.getMaterialPo().setVersionType(versionType);
						materialRequest.getMaterialPo().setVersionNumber(versionNumber);
						materialRequests.add(materialRequest);
					}
				}
			} catch (Exception e) {
				throw new Exception("素材配置文件中文件读取错误!" + e.getMessage());
			}
		}
		return materialRequests;
	}

	public List<String> getMaterialNames(String versionType,String versionNumber){
		
		return materialDao.getMaterialNames(versionType, versionNumber);
	}


	@Transactional(readOnly=false)
	public void deleteMaterial(int id) throws Exception {
		MaterialPO m = materialDao.getMaterialById(id);
		//String isRecommend = m.getIsRecommend();
		/*if("1".equals(isRecommend)){
			//是推荐素材，其后的素材推荐顺序全部减一
			int recommendOrder = Integer.parseInt(m.getRecommendOrder());
			materialDao.updateRecommendOrder(-1, m.getVersionType(), m.getVersionNumber(),recommendOrder);
		}
		String category = m.getCategory();
		int categoryOrder = Integer.parseInt(m.getCategoryOrder());
		materialDao.updateCategoryOrder(-1, m.getVersionType(), m.getVersionNumber(), category,categoryOrder);*/
		materialDao.deleteMaterial(id);
		materialDao.clearMaterialCacheRegion();
	}

	@Transactional
	public void addMaterial(MaterialPO m, String savePath) throws Exception {
		File iconFile = new File(savePath + "\\" + m.getIconName());
		File materialFile = new File(savePath + "\\" + m.getMaterialName());
		m.setIconMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(iconFile)));
		m.setMaterialMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(materialFile)));
		m.setMaterialDownloadUrl(materialUpdateConfig.getIisURLRoot()+"/"+m.getMaterialName());
		m.setIconDownloadUrl(materialUpdateConfig.getIisURLRoot()+"/"+m.getIconName());
		List<String> uuids = materialDao.getMaterialUuids();
		for(String uuid : uuids){
			if(uuid.equals(m.getUuid())){
				throw new RuntimeException("素材已经存在，uuid为："+m.getUuid());
			}
		}
		materialDao.saveMaterial(m);
		MaterialLatest ml = new MaterialLatest(m);
		latestMaterialDao.saveLatestMaterial(ml);
		materialDao.clearMaterialCacheRegion();
	}

	public List<MaterialPO> findAllMaterialList(MaterialPO mp) {
		return materialDao.getMaterials(mp);
	}

	@Transactional(readOnly=false)
	public void addHotMaterials(List<MaterialPO> hotMaterials,String versionType,String versionNumber) throws IOException {
		
		String nginxRoot = Global.getConfig("nginx.root");
		String nginxLocalMaterialPath = nginxRoot+Constants.MATERIALS_DIRECTORY+"\\" + versionType+"\\"+versionNumber+"\\";
		
		//String destFolderPath = workspaceRoot+"\\local";
		File destFolder = new File(nginxLocalMaterialPath);
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		} 
		String ftpMaterialPath = materialUpdateConfig.getFtpLocalRoot()+versionType+"\\"+versionNumber+"\\";
		
		/*FileUtils.copyFileToDirectory(new File(ftpMaterialPath+"\\"+m.getIconName()), destFolder);
		FileUtils.copyFileToDirectory(new File(ftpMaterialPath+"\\"+m.getMaterialName()), destFolder);*/
		FileUtils.copyDirectory(new File(ftpMaterialPath), destFolder,true);
		materialDao.updateRecommendOrder(hotMaterials.size(),versionType,versionNumber);
		for(MaterialPO m : hotMaterials){
			File iconFile = new File(destFolder.getAbsolutePath() + "\\" + m.getIconName());
			File materialFile = new File(destFolder.getAbsolutePath() + "\\" + m.getMaterialName());
			m.setIconMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(iconFile)));
			m.setMaterialMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(materialFile)));
			m.setMaterialDownloadUrl(materialUpdateConfig.getIisURLRoot()+m.getVersionType()+"/"+m.getVersionNumber()+"/"+m.getMaterialName());
			m.setIconDownloadUrl(materialUpdateConfig.getIisURLRoot()+m.getVersionType()+"/"+m.getVersionNumber()+"/"+m.getIconName());
			materialDao.saveMaterial(m);
		}
		
		materialDao.clearMaterialCacheRegion();
	}

	/*@Transactional(readOnly=false,rollbackFor=Exception.class)
	public void addHotMaterials(Map<String, List<MaterialPO>> hotMaterials,
			String versionType, String versionNumber, int number)
			throws IOException,RuntimeException {
		String nginxRoot = Global.getConfig("nginx.root");
		String nginxLocalMaterialPath = nginxRoot + Constants.MATERIALS_DIRECTORY+"\\"+ versionType+"\\"+versionNumber+"\\";
		File destFolder = new File(nginxLocalMaterialPath);
		if (!destFolder.exists()) {
			destFolder.mkdirs();
		} 
		//美术传到ftp上的路径，里面是最新的素材
		//String ftpMaterialMeishuPath = materialUpdateConfig.getFtpLocalRoot()+"ios\\1.0.0\\";
		String ftpMaterialPath = materialUpdateConfig.getFtpLocalRoot()+versionType+"\\"+versionNumber+"\\";
		
		FileUtils.copyDirectory(new File(ftpMaterialPath), destFolder,true);
		materialDao.updateRecommendOrder(number,versionType,versionNumber);
		Iterator<String> it=hotMaterials.keySet().iterator();
		List<String> materialNames = getMaterialNames(versionType, versionNumber);
		while(it.hasNext()){
			String category = it.next().toString();
			List<MaterialPO> materials = hotMaterials.get(category);
			materialDao.updateCategoryOrder(materials.size(), versionType, versionNumber, category);
			for(MaterialPO m : materials){
				String uuid = m.getUuid();
				for(String name : materialNames){
					if(name.equals(uuid)){
						throw new RuntimeException("material uuid: "+uuid + "exists!"); 
					}
				}
				
				File iconFile = new File(destFolder.getAbsolutePath() + "\\" + m.getIconName());
				File materialFile = new File(destFolder.getAbsolutePath() + "\\" + m.getMaterialName());
				if(!iconFile.isFile() || !materialFile.isFile()){
					throw new RuntimeException("iconFile or materialFile can not find！");
				}
				m.setIconMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(iconFile)));
				m.setMaterialMD5(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(materialFile)));
				m.setMaterialDownloadUrl(materialUpdateConfig.getIisURLRoot()+m.getVersionType()+"/"+m.getVersionNumber()+"/"+m.getMaterialName());
				m.setIconDownloadUrl(materialUpdateConfig.getIisURLRoot()+m.getVersionType()+"/"+m.getVersionNumber()+"/"+m.getIconName());
				String gender = m.getGender();
				if(gender.equals("1") || gender.equals("0")){
					materialDao.saveMaterial(m);
				}else if(gender.equals("-1")){
					m.setGender("1");
					materialDao.saveMaterial(m);
					MaterialPO mNew = new MaterialPO();
					BeanUtils.copyProperties(m, mNew);
					mNew.setGender("0");
					materialDao.saveMaterial(mNew);
				}else {
					throw new RuntimeException("gender can only be -1 or 0 or 1");
				}
				
			}
		}
		materialDao.clearMaterialCacheRegion();
	}*/

	public MaterialPO getMaterialById(int id) {
		return materialDao.getMaterialById(id);
	}

	public void updateMaterial(MaterialPO materialPO) {
		materialPO.setUpdateTime(new Date());
		/*if(StringUtils.isEmpty(materialPO.getRecommendOrder())){
			materialPO.setRecommendOrder(null);
		}*/
		materialDao.updateMaterial(materialPO);
		materialDao.clearMaterialCacheRegion();
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(new File("d:\\2d_H003.zip"))));
	}

	public Map<String, String> getMaterialMd5s(String iconName,
			String materialName, String versionType, String versionNumber) throws Exception {
		String nginxRoot = Global.getConfig("nginx.root");
		String nginxLocalMaterialPath = nginxRoot + Constants.MATERIALS_DIRECTORY+"\\"+ versionType
				+"\\"+versionNumber+"\\";
		File iconFile = new File(nginxLocalMaterialPath+iconName);
		File materialFile = new File(nginxLocalMaterialPath+materialName);
		if(!iconFile.exists() || !materialFile.exists()){
			throw new RuntimeException("file not found!");
		}
		String iconMd5 = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(iconFile));
		String materialMd5 = DigestUtils.md5DigestAsHex(FileCopyUtils.copyToByteArray(materialFile));
		Map<String,String> map = Maps.newHashMap();
		map.put("iconMd5", iconMd5);
		map.put("materialMd5", materialMd5);
		return map;
	}

	public void cleanMaterialCache() {
		SessionFactory sessionFactory = SpringContextHolder.getBean("sessionFactory");
		sessionFactory.evict(MaterialPO.class);
		sessionFactory.evictQueries("materialPO");
	}

	public void deleteMaterialsByIds(int[] id) throws Exception{
		StringBuilder sb = new StringBuilder();
		for(int mid : id){
			sb.append(mid).append(",");
		}
		sb.deleteCharAt(sb.length()-1);
		materialDao.deleteMaterialsByIds(sb.toString());
		materialDao.clearMaterialCacheRegion();
	}

	public void addMaterials(List<MaterialPO> materialPOS) {
		materialDao.saveMaterials(materialPOS);
		materialDao.clearMaterialCacheRegion();
	}

	/*@Override
	public int[] getFrontXMaterials(int frontSize,String versionType,String versionNumber) {
		List<MaterialPO> materialPOs = findAllMaterialList(versionType,versionNumber);
		Map<Integer,List<Integer>> map = new HashMap<Integer, List<Integer>>();

		for (MaterialPO m:materialPOs){
			Integer categoryId = m.getCategoryId();
			if(null == map.get(categoryId)){
				map.put(categoryId,Lists.newArrayList(m.getCategoryOrder()))
			}

		}
		//return materialDao.getFrontXMaterials(frontSize,versionType, versionNumber);

	}*/
}
